// Package __DFS 695-area-island
// @Title __DFS
// @Description
// @Author  == 琳琳也叫王木木 ==  2021/9/7 11:08
// @Create  2021/9/7 11:08
package __DFS

func registerIsland(mat [][]int, i, j, n, m int) int {
	if i < 0 || j < 0 || i >= n || j >= m || mat[i][j] != 1 {
		return 0
	}
	// 将当前岛屿感染
	mat[i][j] = 0
	// 感染其上下左右四个方向
	up := registerIsland(mat, i-1, j, n, m)
	down := registerIsland(mat, i+1, j, n, m)
	left := registerIsland(mat, i, j-1, n, m)
	right := registerIsland(mat, i, j+1, n, m)
	// 这里+1的意思是将当前节点的面积算上
	return up + down + left + right + 1
}

func maxInt(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// MaxAreaOfIsland 获取岛屿的最大面积
func MaxAreaOfIsland(grid [][]int) int {
	n, m := len(grid), len(grid[0])
	maxArea := 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if grid[i][j] == 1 {
				// 执行感染
				temp := registerIsland(grid, i, j, n, m)
				maxArea = maxInt(maxArea, temp)
			}
		}
	}
	return maxArea
}
